//
//  FindEmotion.swift
//  表情键盘
//
//  Created by 陈恒均 on 2018/2/24.
//  Copyright © 2018年 陈恒均. All rights reserved.
//

import UIKit

class FindEmotion: NSObject {
    static let shareInstance : FindEmotion = FindEmotion()
    
    private lazy var manger : EmoticonManger = EmoticonManger()
    
    
    func findAttrString(statusText : String? ,font : UIFont) -> NSMutableAttributedString? {
        
        guard let statusText = statusText else {
            return nil
        }
        let pattern = "\\[.*?\\]" // 匹配表情
        
        guard let regex = try? NSRegularExpression(pattern: pattern, options: []) else{
            return nil
        }
        
        let results = regex.matches(in: statusText, options: [], range: NSRange(location: 0, length: statusText.characters.count))
        let attrMStr = NSMutableAttributedString(string: statusText)
        
        for result in results.reversed() {
            
            //获取chs
            let chs = (statusText as NSString).substring(with: result.range)
            
            guard let pngPath = findPngPath(chs: chs) else{
                return nil
            }
            let attachment = NSTextAttachment()
            attachment.image = UIImage(contentsOfFile: pngPath)
            attachment.bounds = CGRect(x: 0, y: -4, width: font.lineHeight, height: font.lineHeight)
            
            let attImageStr = NSAttributedString(attachment: attachment)
            attrMStr.replaceCharacters(in: result.range, with: attImageStr)
            
            
        }
        return attrMStr
  
    }
    private func findPngPath(chs : String) -> String?{
        for package in manger.packages {
            for emoticon in package.emoticons{
                if emoticon.chs == chs{
                    return emoticon.pngPath
                }
            }
        }
        return nil
    }
}
